package org.redis.cluster.transport.client.support;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArrayList;

import org.redis.cluster.RedisCluster;
import org.redis.cluster.config.ClientConfig;
import org.redis.cluster.plugin.Plugin;
import org.redis.cluster.registry.Registry;
import org.redis.cluster.transport.client.ClientManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultClientManager implements ClientManager,Plugin {
	
	private final static boolean DEFAULT_CACHE_EANBLE=true;
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	private Registry registry;
	
	private boolean cacheEnable=DEFAULT_CACHE_EANBLE;
	
	private Collection<ClientConfig> clientConfigs;
	
	@Override
	public void init(RedisCluster redisCluster) {
		this.registry=redisCluster.getRegistry();
		this.clientConfigs=initClients();
		
		initClientListener();
	}
	
	@Override
	public void destroy() {
	}

	protected void initClientListener() {
		if(!isCacheEnable()) {
			return;
		}
		
		registry.listenClient((String path)->{
			if(logger.isInfoEnabled()) {
				logger.info("监听到后端redis变化,准备更新缓存");
			}
			
			this.clientConfigs=initClients();
		});
	}
	
	protected Collection<ClientConfig> initClients() {
		return new CopyOnWriteArrayList<ClientConfig>(registry.getClients());
	}

	@Override
	public Collection<ClientConfig> getConfigs() {
		Collection<ClientConfig> clientConfigs=null;
		if(isCacheEnable()) {
			clientConfigs=this.clientConfigs;
		}
		else {
			clientConfigs=initClients();
		}
		
		if(clientConfigs==null) {
			return Collections.emptyList();
		}
		
		return clientConfigs;
	}
	
	public void setRegistry(Registry registry) {
		this.registry = registry;
	}
	public Registry getRegistry() {
		return registry;
	}
	public boolean isCacheEnable() {
		return cacheEnable;
	}
	public void setCacheEnable(boolean cacheEnable) {
		this.cacheEnable = cacheEnable;
	}
}